package com.lintpanzer.managers
{
	import flash.events.Event;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.FileFilter;
	
	public class FileManager extends ManagerBase
	{
		private var fileStream:FileStream;
		private var _fileSource:String;
		
		public function FileManager(target:IEventDispatcher=null)
		{
			super(target);
		}
		
		[Bindable (event="FileSourceChanged")]
		public function get fileSource():String{
			return _fileSource;
		}
			
		public function storeFileSource(value:String):void{
			_fileSource = value;
			dispatchEvent(new Event("FileSourceChanged"));
		}
		
		public function openFileDialog():void{
			var file:File = new File();
			var fileFilter:FileFilter = new FileFilter("js","*.js");
			file.browseForOpen("Select JavaScript File",[fileFilter]);
			file.addEventListener(Event.SELECT,function(event:Event):void{
				openFile(event.target as File);
			});
	}
		
		public function openFile(_file:File):void{
			if (fileStream){
				fileStream.close();
			}
			
			fileStream = new FileStream();
			fileStream.addEventListener(Event.COMPLETE,onOpenComplete);
			fileStream.addEventListener(IOErrorEvent.IO_ERROR,onReadIOError);
			fileStream.openAsync(_file,FileMode.READ);
		}
		
		private function onOpenComplete(event:Event):void{
			var fileText:String = fileStream.readUTFBytes(fileStream.bytesAvailable);
			fileStream.close();
			var lineEndPattern:RegExp = new RegExp(File.lineEnding,"g");
			fileText = fileText.replace(lineEndPattern, "\n");
			storeFileSource(fileText);
		}
		
		private function onReadIOError(event:IOErrorEvent):void{
			
		}
	}
}